package leetcode_题库;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/30 9:01 星期二
 */
public class _98_验证二叉搜索树 {

    /**
     * 中序遍历，看最后是不是正序
     * > 2022/08/30 09:25:51
     * 解答成功:
     * 	执行耗时:4 ms,击败了19.29% 的Java用户
     * 	内存消耗:40.7 MB,击败了91.46% 的Java用户
     * @param root
     * @return
     */
    public boolean isValidBST_Ok(TreeNode root) {
        if (root == null) {
            return false;
        }
        Stack<TreeNode> stack = new Stack<>();
        Queue<Integer> keys = new ArrayDeque<>();
        stack.add(root);
        TreeNode cur = root.left;
        while (!stack.isEmpty()) {
            if (cur != null) {
                stack.add(cur);
                cur = cur.left;
            } else {
                TreeNode curPre = stack.pop();
                keys.add(curPre.val);
                if (curPre.right!=null){
                    stack.push(curPre.right);
                    cur = curPre.right.left;
                }
            }
        }

        int integer = keys.poll();
        for (Integer key : keys) {
            int k = keys.poll();
            if (k <= integer) {
                return false;
            }
            integer = k;
        }
        return true;
    }

    /**
     * 这个不行，因为必须[5,4,6,null,null,3,7]，3作为右子树的结点，必须大于根结点5，递归就很难实现
     * @param root
     * @return
     */
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (root.left != null && root.left.val >= root.val){
            return false;
        }
        if (root.right != null && root.right.val <= root.val){
            return false;
        }
        return isValidBST(root.left) && isValidBST(root.right);
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
